package com.cloudbroker.bcs.common.jres.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.cloudbroker.bcs.common.jres.constants.T2ErrorCode;
import com.cloudbroker.bcs.common.jres.constants.T2Fields;
import com.cloudbroker.bcs.common.util.ValueUtil;

public class T2VOUtil {

    public static Map<String, Object> genSuccessResult() {
        Map<String, Object> result = new HashMap<String, Object>();
        return setSuccessResult(result);
    }
    
    public static Map<String, Object> genSuccessResult(String errorInfo) {
        return genErrorResult(T2ErrorCode.SUCCESS, errorInfo);
    }
    
    public static Map<String, Object> setSuccessResult(Map<String, Object> result) {
        result.put(T2Fields.ERROR_NO, T2ErrorCode.SUCCESS);
        return result;
    }
    
    public static Map<String, Object> setSuccessResult(Map<String, Object> result, String errorInfo) {
        return setErrorResult(result, T2ErrorCode.SUCCESS, errorInfo);
    }
    
    public static Map<String, Object> genCommonErrorResult(String errorInfo) {
        return genErrorResult(T2ErrorCode.CLI_COMMON_ERROR, errorInfo);
    }
    
    public static Map<String, Object> genTimeoutErrorResult(String errorInfo) {
        return genErrorResult(T2ErrorCode.CLI_TIMEOUT, errorInfo);
    }
    
    public static Map<String, Object> genErrorResult(String errorNo, String errorInfo) {
        Map<String, Object> result = new HashMap<String, Object>();
        return setErrorResult(result, errorNo, errorInfo);
    }
    
    public static Map<String, Object> setErrorResult(Map<String, Object> result, String errorNo, String errorInfo) {
        result.put(T2Fields.ERROR_NO, errorNo);
        result.put(T2Fields.ERROR_INFO, errorInfo);
        return result;
    }
    
    public static boolean isSuccess(Map<String, Object> result) {
        return null != result
                && T2ErrorCode.SUCCESS.equals(ValueUtil.getString(result.get(T2Fields.ERROR_NO),
                        T2ErrorCode.SUCCESS));
    }
    
    public static boolean isErrorOf(Map<String, Object> result, String errorNo) {
        if (null != result) {
            Object error_no = result.get(T2Fields.ERROR_NO);
            if (null != error_no) {
                return error_no.equals(errorNo);
            }
        }
        return false;
    }
    
    public static boolean isErrorIn(Map<String, Object> result, String... errorNos) {
        if (null != result) {
            Object error_no = result.get(T2Fields.ERROR_NO);
            if (null != error_no && null != errorNos && 0 < errorNos.length) {
                return -1 != Arrays.binarySearch(errorNos, error_no);
            }
        }
        return false;
    }
    
}
